# wzry_api.py - FastAPI服务
"""
王者荣耀查询API服务
提供REST API接口和token认证
"""

from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional, Dict, Any  # 添加了 Dict 和 Any 的导入
from datetime import datetime
import time
from wzry_core import device_pool, query_engine, PlayerResult


# 配置
API_TOKENS = {
    "wzry_admin_token",
    "wzry_user1_token", 
    "wzry_user2_token"
}

security = HTTPBearer()


# 数据模型
class SearchRequest(BaseModel):
    player_name: str
    timeout: Optional[int] = 30


class SearchResponse(BaseModel):
    success: bool
    message: str
    data: List[Dict[str, Any]]  # 修复了类型注解
    query_time: float
    device_used: Optional[str] = None


class DeviceRequest(BaseModel):
    device_id: str


class StatusResponse(BaseModel):
    devices: Dict[str, Any]  # 修复了类型注解
    total_devices: int
    available_devices: int


# 认证依赖
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    token = credentials.credentials
    # 简单的token验证
    if token not in API_TOKENS:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的访问令牌"
        )
    return token


# 创建FastAPI应用
app = FastAPI(
    title="王者荣耀玩家查询API",
    description="高性能多设备王者荣耀玩家查询系统",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"], 
    allow_headers=["*"],
)


@app.get("/")
async def root():
    """API根路径"""
    return {
        "message": "王者荣耀玩家查询API",
        "version": "1.0.0",
        "docs": "/docs"
    }


@app.post("/devices/add", dependencies=[Depends(verify_token)])
async def add_device(request: DeviceRequest):
    """添加设备到连接池"""
    try:
        success = device_pool.add_device(request.device_id)
        if success:
            return {"success": True, "message": f"设备 {request.device_id} 添加成功"}
        else:
            return {"success": False, "message": f"设备 {request.device_id} 添加失败"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加设备失败: {str(e)}")


@app.delete("/devices/{device_id}", dependencies=[Depends(verify_token)])
async def remove_device(device_id: str):
    """从连接池移除设备"""
    try:
        device_pool.remove_device(device_id)
        return {"success": True, "message": f"设备 {device_id} 移除成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"移除设备失败: {str(e)}")


@app.get("/devices/status", dependencies=[Depends(verify_token)])
async def get_devices_status():
    """获取所有设备状态"""
    try:
        status = device_pool.get_device_status()
        available_count = sum(1 for dev in status.values() if dev["connected"] and not dev["busy"])
        
        return StatusResponse(
            devices=status,
            total_devices=len(status),
            available_devices=available_count
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取设备状态失败: {str(e)}")


@app.post("/search", dependencies=[Depends(verify_token)])
async def search_player(request: SearchRequest):
    """搜索玩家"""
    try:
        start_time = time.time()
        
        # 执行搜索
        results, message = query_engine.search_player(request.player_name, request.timeout)
        
        # 计算查询时间
        query_time = time.time() - start_time
        
        # 转换结果格式
        data = []
        for result in results:
            data.append({
                "nickname": result.nickname,
                "role_name": result.role_name, 
                "server_info": result.server_info,
                "rank_info": result.rank_info
            })
        
        return SearchResponse(
            success=len(results) > 0,
            message=message,
            data=data,
            query_time=query_time
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"搜索失败: {str(e)}")


@app.get("/health")
async def health_check():
    """健康检查"""
    device_status = device_pool.get_device_status()
    available_devices = sum(1 for dev in device_status.values() if dev["connected"] and not dev["busy"])
    
    return {
        "status": "healthy" if available_devices > 0 else "no_devices",
        "timestamp": datetime.now().isoformat(),
        "available_devices": available_devices,
        "total_devices": len(device_status)
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)